/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Deal.PersonalInformation.Logic;

import data.DAO.IEquivalentCouponStore;
import data.pojo.EquivalentCoupon;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;

/**
 *
 * @author 伯乐
 */
public class EquivalentCouponLogic extends CouponLogic{

    private IEquivalentCouponStore eqCouponDS = new IEquivalentCouponStore();
    
    @Override
    public boolean removeCoupon(String userID, List<String> couponList, List<Integer> numList) {
        if(couponList == null || numList == null ){ return false; }
        if(couponList.size()!=numList.size() || couponList.isEmpty()){ return false; }
        List<EquivalentCoupon> ecList = eqCouponDS.searchObjectsByAttr("customerID", userID);
        List<EquivalentCoupon> tempList = new ArrayList();//存放要被删除的优惠券
        for(EquivalentCoupon ec:ecList){
            int loc = couponList.indexOf(ec.getId());
            if(loc!=-1){ //存在对应优惠券
                int c_num = ec.getNumber();
                int number = numList.get(loc);
                if(number>ec.getMaxnumber()){ return false; }
                if(c_num>number){
                    ec.setNumber(c_num-number);
                } else if(c_num==number){
                    tempList.add(ec);
                } else {
                    return false; 
                }
            }
        }
        boolean valid = true;
        for(EquivalentCoupon ec:tempList){
            valid &= ecList.remove(ec);
        }
        if(valid){ eqCouponDS.update(ecList); }
        return valid;
    }
    
    @Override
    public Vector getCoupon(String userID) {
        List<EquivalentCoupon> ecList = eqCouponDS.searchObjectsByAttr("customerID", userID);
        if(ecList == null ){ return null;}
        Vector<Vector<String>> ecVector = new Vector();
        for(EquivalentCoupon ec : ecList){
            ecVector.add( toEqStringArray(ec) );
        }
        return ecVector;
    }
    
    private Vector<String> toEqStringArray(EquivalentCoupon ec) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Vector<String> list = new Vector<String>();
        
        list.add(ec.getId());
        list.add(String.valueOf(ec.getPrice()));
        list.add(String.valueOf(ec.getNumber()));
        list.add(String.valueOf(ec.getMaxnumber()));
        Date startDay = ec.getStartDay();
        Date endDay = ec.getEndDay();
        list.add(startDay==null?"":sdf.format(startDay));
        list.add(endDay==null?"":sdf.format(endDay));
        
        return list;
    }

}
